using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;

namespace FreeHTPC
{
	sealed class Win32API
	{
		public const int WM_COPYDATA = 74;
		
		[StructLayout(LayoutKind.Sequential)]
		public struct COPYDATASTRUCT
		{
			public Int32 dwData;
			public Int32 cbData;
			public IntPtr lpData;
		}

		[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
		public static extern IntPtr SendMessage(HandleRef hWnd, uint Msg, IntPtr wParam, StringBuilder lParam);
		[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
		public static extern IntPtr SendMessage(HandleRef hWnd, uint Msg, IntPtr wParam, IntPtr cd);
		public static IntPtr SendMessage(HandleRef hWnd, uint Msg, IntPtr wParam, COPYDATASTRUCT cd)
		{
			IntPtr pnt = Marshal.AllocHGlobal(Marshal.SizeOf(cd));
			try
			{
				// Copy the struct to unmanaged memory.
				Marshal.StructureToPtr(cd, pnt, false);
				return SendMessage(hWnd, WM_COPYDATA, wParam, pnt);
			}
			finally
			{
				// Free the unmanaged memory.
				Marshal.FreeHGlobal(pnt);
			}
		}
		
		public static IntPtr SendMessage_WM_COPYDATA(HandleRef hWnd,IntPtr wParam, Int32 dwData, byte[] lpData )
		{
			COPYDATASTRUCT cd = new COPYDATASTRUCT();
			cd.dwData = dwData;
			if(lpData==null)
			{
				cd.cbData = 0;
				cd.lpData = IntPtr.Zero;
				return SendMessage(hWnd, WM_COPYDATA, wParam, cd);
			}
			else
			{
				cd.cbData = lpData.Length;
				GCHandle h = GCHandle.Alloc(lpData, GCHandleType.Pinned);
				try
				{
					cd.lpData = h.AddrOfPinnedObject();
					return SendMessage(hWnd, WM_COPYDATA, wParam, cd);
				}
				finally
				{
					h.Free();
				}
			}
		}
		public static IntPtr SendMessage_WM_COPYDATA(HandleRef hWnd,IntPtr wParam, Int32 dwData, string lpData, Encoding stringEncoding )
		{
			if(lpData==null)
				return SendMessage_WM_COPYDATA(hWnd, wParam, dwData, null);
			else
				return SendMessage_WM_COPYDATA(hWnd, wParam, dwData, stringEncoding.GetBytes(lpData + '\0'));
		}
		
		public static IntPtr SendMessage_WM_GETTEXT(HandleRef hWnd, StringBuilder lpString)
		{
			return SendMessage(hWnd, 1, new IntPtr(lpString.Capacity), lpString);
		}
				
		
		
	}
}
